<template>
    <div class="products">
        <div class="products-header">
            <h3>我的商品</h3>
            <el-button type="primary" @click="handleAdd">
                <el-icon>
                    <Plus />
                </el-icon>
                发布商品
            </el-button>
        </div>

        <!-- 筛选条件 -->
        <div class="filter-container">
            <el-form :inline="true" :model="filterForm">
                <el-form-item label="商品状态">
                    <el-select v-model="filterForm.status" placeholder="全部状态" clearable>
                        <el-option label="在售" value="on_sale" />
                        <el-option label="已售" value="sold" />
                        <el-option label="下架" value="off_shelf" />
                    </el-select>
                </el-form-item>
                <el-form-item label="商品分类">
                    <el-select v-model="filterForm.category" placeholder="全部分类" clearable>
                        <el-option v-for="item in categories" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="resetFilter">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 商品列表 -->
        <el-table :data="filteredProducts" style="width: 100%" v-loading="loading">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column label="商品图片" width="120">
                <template #default="{ row }">
                    <el-image :src="row.images[0]" :preview-src-list="row.images" fit="cover" class="product-image" />
                </template>
            </el-table-column>
            <el-table-column prop="name" label="商品名称" min-width="200" />
            <el-table-column prop="category" label="分类" width="120" />
            <el-table-column prop="price" label="价格" width="120">
                <template #default="{ row }">
                    ¥{{ row.price }}
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                    <el-tag :type="getStatusType(row.status)">
                        {{ getStatusText(row.status) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="created_at" label="发布时间" width="180" />
            <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                    <el-button-group>
                        <el-button type="primary" size="small" @click="handleEdit(row)">
                            编辑
                        </el-button>
                        <el-button type="danger" size="small" @click="handleDelete(row)">
                            删除
                        </el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 商品表单对话框 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="商品名称" prop="name">
                    <el-input v-model="form.name" />
                </el-form-item>
                <el-form-item label="商品分类" prop="category">
                    <el-select v-model="form.category" placeholder="请选择分类">
                        <el-option v-for="item in categories" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="商品价格" prop="price">
                    <el-input-number v-model="form.price" :min="0" :precision="2" :step="0.1" />
                </el-form-item>
                <el-form-item label="商品图片" prop="images">
                    <el-upload action="#" list-type="picture-card" 
                        :auto-upload="false"
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove" 
                        :before-upload="beforeUpload"
                        :file-list="fileList"
                        :limit="6">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="商品描述" prop="description">
                    <el-input v-model="form.description" type="textarea" :rows="4" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 图片预览对话框 -->
        <el-dialog v-model="previewVisible">
            <img w-full :src="previewImage" alt="Preview Image" />
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import { getImageUrl } from '@/utils/image'
import request from '@/utils/request'

// 筛选表单
const filterForm = reactive({
    status: '',
    category: ''
})

// 商品列表数据
const products = ref([
    {
        id: 1,
        name: '二手笔记本电脑',
        images: ['https://picsum.photos/200/200?random=1'],
        category: '电子产品',
        price: 2999,
        status: 'on_sale',
        created_at: '2024-03-20 10:00:00'
    },
    {
        id: 2,
        name: '大学英语四级词汇书',
        images: ['https://picsum.photos/200/200?random=2'],
        category: '书籍',
        price: 20,
        status: 'sold',
        created_at: '2024-03-19 15:30:00'
    }
])

// 筛选后的商品列表
const filteredProducts = computed(() => {
    let result = [...products.value]

    // 按状态筛选
    if (filterForm.status) {
        result = result.filter(item => item.status === filterForm.status)
    }

    // 按分类筛选
    if (filterForm.category) {
        result = result.filter(item => item.category === filterForm.category)
    }

    return result
})

// 分类列表
const categories = [
    { id: 1, name: '电子产品' },
    { id: 2, name: '书籍' },
    { id: 3, name: '生活用品' },
    { id: 4, name: '服装' },
    { id: 5, name: '其他' }
]

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)
const loading = ref(false)

// 对话框数据
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref<FormInstance>()
const form = reactive({
    id: 0,
    name: '',
    category: '',
    price: 0,
    images: [] as string[],
    description: ''
})

// 表单验证规则
const rules = reactive<FormRules>({
    name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    category: [
        { required: true, message: '请选择商品分类', trigger: 'change' }
    ],
    price: [
        { required: true, message: '请输入商品价格', trigger: 'blur' }
    ],
    images: [
        { required: true, message: '请上传商品图片', trigger: 'change' }
    ],
    description: [
        { required: true, message: '请输入商品描述', trigger: 'blur' }
    ]
})

// 图片上传相关
const fileList = ref<UploadProps['fileList']>([])
const previewVisible = ref(false)
const previewImage = ref('')

// 获取状态类型
const getStatusType = (status: string) => {
    const types: Record<string, string> = {
        on_sale: 'success',
        sold: 'info',
        off_shelf: 'warning'
    }
    return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
    const texts: Record<string, string> = {
        on_sale: '在售',
        sold: '已售',
        off_shelf: '下架'
    }
    return texts[status] || status
}

// 处理搜索
const handleSearch = async () => {
    loading.value = true
    try {
        // 构建参数
        const params = {
            page: currentPage.value - 1,
            limit: pageSize.value
        }
        
        if (filterForm.status) {
            params.status = filterForm.status
        }
        
        if (filterForm.category) {
            params.category = filterForm.category
        }
        
        // 调用API获取用户商品列表
        const response = await request.get('/user/products', { params })
        
        if (response && response.code === 200 && response.data) {
            products.value = response.data.content.map(item => ({
                id: item.id,
                name: item.name,
                category: item.categoryName || '未分类',
                categoryId: item.categoryId,
                price: item.price,
                status: getStatusValue(item.status),
                description: item.description,
                images: item.imageUrls || (item.mainImageUrl ? [item.mainImageUrl] : []),
                created_at: item.createTime || item.createdAt
            }))
            
            total.value = response.data.totalElements || 0
        } else {
            ElMessage.error(response?.message || '获取商品列表失败')
            products.value = []
            total.value = 0
        }
    } catch (error) {
        console.error('获取商品列表失败:', error)
        ElMessage.error('获取商品列表失败')
        products.value = []
        total.value = 0
    } finally {
        loading.value = false
    }
}

// 状态转换函数
const getStatusValue = (status) => {
    if (status === 1 || status === '在售' || status === 'selling') return 'on_sale'
    if (status === 2 || status === '已售' || status === 'sold') return 'sold'
    if (status === 3 || status === '已下架' || status === 'off_shelf') return 'off_shelf'
    return status
}

// 重置筛选条件
const resetFilter = () => {
    filterForm.status = ''
    filterForm.category = ''
    handleSearch()
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
    pageSize.value = val
    handleSearch()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
    currentPage.value = val
    handleSearch()
}

// 处理添加商品
const handleAdd = () => {
    dialogTitle.value = '发布商品'
    dialogVisible.value = true
    // 重置表单
    Object.assign(form, {
        id: 0,
        name: '',
        category: '',
        price: 0,
        images: [],
        description: ''
    })
}

// 处理编辑商品
const handleEdit = async (row: any) => {
    dialogTitle.value = '编辑商品'
    dialogVisible.value = true
    
    // 填充表单数据
    form.id = row.id
    form.name = row.name
    form.category = row.category
    form.price = row.price
    form.description = row.description
    form.images = [...(row.images || [])]
    
    // 重置文件列表
    fileList.value = (row.images || []).map((url: string, index: number) => ({
        name: `image-${index}`,
        url: url,
        uid: `existing-${index}`
    }))
}

// 处理删除商品
const handleDelete = (row: any) => {
    ElMessageBox.confirm(
        '确定要删除该商品吗？删除后将无法恢复。',
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            const response = await request.delete(`/products/${row.id}`)
            if (response && response.code === 200) {
                ElMessage.success('商品已成功删除')
                // 刷新商品列表
            handleSearch()
            } else {
                ElMessage.error(response?.message || '删除失败')
            }
        } catch (error) {
            console.error('删除商品失败:', error)
            ElMessage.error('删除失败，请稍后重试')
        }
    }).catch(() => {
        // 用户取消删除
        ElMessage.info('已取消删除')
    })
}

// 处理图片预览
const handlePictureCardPreview = (file: any) => {
    previewImage.value = file.url || URL.createObjectURL(file.raw)
    previewVisible.value = true
}

// 处理图片移除
const handleRemove = (file: any) => {
    // 如果是已有图片（有URL）
    if (file.url && form.images.includes(file.url)) {
    const index = form.images.indexOf(file.url)
    if (index !== -1) {
        form.images.splice(index, 1)
    }
}

    // 更新文件列表
    const index = fileList.value.findIndex(f => f.uid === file.uid)
        if (index !== -1) {
        fileList.value.splice(index, 1)
    }
}

// 上传前的验证
const beforeUpload = (file: File) => {
    const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isJPGOrPNG) {
        ElMessage.error('上传图片只能是 JPG/PNG 格式!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!')
        return false
    }
    return true
}

// 处理表单提交
const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // 创建FormData对象
                const formData = new FormData()
                
                // 添加基本信息
                formData.append('name', form.name)
                formData.append('categoryId', form.category)
                formData.append('price', String(form.price))
                formData.append('description', form.description)
                formData.append('condition', '9成新') // 默认值，可根据实际需求调整
                
                // 添加已有图片URL
                const existingImages = fileList.value
                    .filter(file => file.url && !file.raw)
                    .map(file => file.url)
                
                existingImages.forEach(url => {
                    formData.append('imageUrls', url)
                })
                
                // 添加新上传的文件
                const newFiles = fileList.value
                    .filter(file => file.raw)
                    .map(file => file.raw)
                
                newFiles.forEach(file => {
                    formData.append('files', file)
                })
                
                // 发送请求
                let response
                if (form.id) {
                    // 更新商品
                    response = await request.put(`/products/${form.id}`, formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    })
                } else {
                    // 新增商品
                    response = await request.post('/products', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    })
                }
                
                if (response && response.code === 200) {
                    ElMessage.success(form.id ? '商品更新成功' : '商品发布成功')
                dialogVisible.value = false
                handleSearch()
                } else {
                    ElMessage.error(response?.message || '操作失败')
                }
            } catch (error) {
                console.error('保存商品失败:', error)
                ElMessage.error('保存失败')
            }
        }
    })
}
</script>

<style scoped>
.products {
    padding: 20px;
    background-color: #f8f9fa;
}

.products-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding: 20px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.products-header h3 {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: #2c3e50;
    position: relative;
    padding-left: 15px;
}

.products-header h3::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 24px;
    background: #409eff;
    border-radius: 2px;
}

.filter-container {
    margin-bottom: 30px;
    padding: 25px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

:deep(.el-table) {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

:deep(.el-table th) {
    background-color: #f8f9fa;
    color: #2c3e50;
    font-weight: 600;
    padding: 12px 0;
}

:deep(.el-table td) {
    padding: 12px 0;
}

.product-image {
    width: 80px;
    height: 80px;
    border-radius: 8px;
    object-fit: cover;
    transition: transform 0.3s ease;
}

.product-image:hover {
    transform: scale(1.05);
}

:deep(.el-tag) {
    border-radius: 4px;
    padding: 0 12px;
    height: 28px;
    line-height: 26px;
    font-weight: 500;
}

:deep(.el-button-group) {
    display: flex;
    gap: 8px;
}

:deep(.el-button) {
    border-radius: 6px;
    padding: 8px 16px;
    font-weight: 500;
    transition: all 0.3s ease;
}

:deep(.el-button--primary) {
    background: linear-gradient(135deg, #409eff, #36a3f7);
    border: none;
}

:deep(.el-button--primary:hover) {
    background: linear-gradient(135deg, #36a3f7, #409eff);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

:deep(.el-button--danger) {
    background: linear-gradient(135deg, #f56c6c, #e74c3c);
    border: none;
}

:deep(.el-button--danger:hover) {
    background: linear-gradient(135deg, #e74c3c, #f56c6c);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}

.pagination-container {
    margin-top: 30px;
    display: flex;
    justify-content: flex-end;
    padding: 20px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

:deep(.el-pagination) {
    --el-pagination-button-bg-color: white;
    --el-pagination-hover-color: #409eff;
}

:deep(.el-pagination .el-pager li) {
    border-radius: 6px;
    font-weight: 500;
}

:deep(.el-pagination .el-pager li.active) {
    background: linear-gradient(135deg, #409eff, #36a3f7);
    color: white;
}

:deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;
}

:deep(.el-dialog__header) {
    padding: 20px;
    margin: 0;
    background: #f8f9fa;
    border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
    font-size: 18px;
    font-weight: 600;
    color: #2c3e50;
}

:deep(.el-dialog__body) {
    padding: 30px;
}

:deep(.el-dialog__footer) {
    padding: 20px;
    background: #f8f9fa;
    border-top: 1px solid #ebeef5;
}

:deep(.el-form-item__label) {
    font-weight: 500;
    color: #2c3e50;
}

:deep(.el-input__inner),
:deep(.el-textarea__inner) {
    border-radius: 6px;
    transition: all 0.3s ease;
}

:deep(.el-input__inner:focus),
:deep(.el-textarea__inner:focus) {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-upload--picture-card) {
    border-radius: 8px;
    transition: all 0.3s ease;
}

:deep(.el-upload--picture-card:hover) {
    border-color: #409eff;
    transform: translateY(-2px);
}
</style>